// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

Event.observe(window, 'load', floatingTools, false);
Event.observe(window, 'scroll', floatingTools, false);
Event.observe(window, 'resize', floatingTools, false);

Event.observe(window, 'load', display_asset, false);

Event.observe(window, 'load', browser_fixups, false);
Event.observe(window, 'load', add_login_message, false);
Event.observe(window, 'load', highlight_on_load, false);

function floatingTools() {
	try {
		var navigation_box = dojo.byId('go_to');
		var el = dojo.byId('static_top');
		var box_top = (el.offsetTop + 75);
		logo = dojo.byId('floating_identifier');
		
		var scrollOffset = dojo.html.getScroll().offset;
		var scrollY = scrollOffset.y;
		
		if (scrollY >= box_top) {
			navigation_box.style.position = "fixed";
			navigation_box.style.padding = "22px 0 0 0";
			logo.style.display = "inline";
		}
		else {
			navigation_box.style.position = "relative";
			navigation_box.style.padding = "7px 0 0 0";
			logo.style.display = "none";
		}
	} 
	catch (Error) {
	}
}

// Window shade functions
function showBox(ele) {
	resetBox(ele);
}
function closeBox(ele) {
	document.getElementById(ele.id+"Show").style.display = "none";
}
function resetBox(ele) {
		var strId = ele.id + "Show";
		var obj = document.getElementById(strId);
	
		if (ele.className.indexOf("_open") > 0 )
			obj.style.display = "inline";
		else
			obj.style.display = "none";
			ele.className = (/_open/.test(ele.className)) ? ele.className.replace('_open', '_close') : ele.className.replace('_close', '_open');
}

function showDOIbutton() {
	document.getElementById("doi_search_button").style.display = "inline";
}

function display_asset(){
	try {
		var asset_source = document.getElementById('asset_source');
		var asset_url = asset_source.getAttribute('src');
		var browser_found = BrowserDetect.browser
		
		if (browser_found == "Explorer") {
			$('asset_source').update('<object data="' + asset_url + '" type="application/pdf" width=100% height=80%></object>');
		}
			new Event.observe($('asset_display'), 'load', Element.hide('spinner'), false)
	} 
	catch (Error) {
	//Handle errors here
	}
}

function browser_fixups(){
    var browser_found = BrowserDetect.browser
    try {
        if (browser_found == "Safari") {
            document.getElementById("content").style.margin = "55px 0px 50px 0px";
            document.getElementById("container").style.margin = "45px 10px 25px 0px";
        }
    } 
    catch (Error) {
        //Be quiet.
    }
}

function add_login_message(){
    try {
		//check to see if this is a page that has a subscriber_label div
        var subscriber_div = document.getElementById("subscriber_label")
        if (subscriber_div) {
            new Ajax.Request('/articles/subscriber_label', {
                asynchronous: true,
                evalScripts: true
            });
            return false;
        }
    } 
    catch (Error) {
        //Be quiet.
    }
}

function highlight_on_load() {
  // Get search string
  search_terms_empty_test = ""
  if (/search/.test(window.location.search)) {
    var search_string = get_search_string();
    // Starting node, parent to all nodes you want to search
    var textContainerNode = document.getElementById("container");

    // Split search terms on '|' and iterate over resulting array
    var search_terms = search_string.split('|');
	var search_info = ''
	search_info += '<div class="article_search_results_notice">';
	search_info +=	'<div>Search Results for:</div>';
	search_info +=	'<div style="padding-left: 12px;">';

	for (var i = 0; i < search_terms.length; i++) {
	    var quote_test = search_terms[i].search("%22")
	    if (quote_test != -1) {
			//Loop thru each term after quote is found 
			//to group these search terms...
			var quoted_text = '';
			for (var s = i; s < search_terms.length; s++) {
				var end_quote_test = search_terms[s].search("%22")
				if (s == i) {
					//start of quoted text
					quoted_text += search_terms[s];
					quoted_text = quoted_text.replace(/\%22|\+/g, "");
					quoted_text += " ";
				} else if (end_quote_test != -1) {
					//end of quoted text
					quoted_text += search_terms[s];
					quoted_text = quoted_text.replace(/\%22|\+/g, "");
					quoted_text += " ";
					i = s //- 1;
					break;
				} else {
					//middle of quoted text
                    quoted_text += search_terms[s];
					quoted_text += " ";
				};
			};
            var regex = new RegExp(">([^<]*)?(" + quoted_text + ")([^>]*)?<", "ig");
            highlightTextNodes(textContainerNode, regex, s);
            search_info += '<span class="search_term_highlight">' + quoted_text + '</span> ';
		} else {
			//put spaces around single characters 
			//("a dog" won't highlight the "a" in "cat")
			if (search_terms[i].length == 1) {
				search_term = " " + search_terms[i] + " ";
			}
			else {
				search_term = search_terms[i];
			};
			// The regex is the secret, it prevents text within tag declarations to be affected
			var regex = new RegExp(">([^<]*)?(" + search_term + ")([^>]*)?<", "ig");
			highlightTextNodes(textContainerNode, regex, i);
			search_info += '<span class="search_term_highlight">' + search_terms[i] + '</span> ';
			search_terms_empty_test += search_terms[i];
		};
	};

	search_info +=	'</div>';
	search_info += '</div>';
    // Create div describing the search    
    if (search_terms_empty_test != "") {
        var search_term_div = document.createElement("H2");
        search_term_div.className = 'search_terms';
        search_term_div.innerHTML = search_info;
        
        // Insert as very first child in searched node
        textContainerNode.insertBefore(search_term_div, textContainerNode.childNodes[0]);
    }
  }
}

// Pull the search string out of the URL
function get_search_string() {
  // Return sanitized search string if it exists
  //var raw_search_string = window.location.search.replace(/[a-zA-Z0-9\?\&\=\%\#]+search\=(\w+)(\&.*)?/,"$1");
  var raw_search_string = window.location.search.replace(/[a-zA-Z0-9\?\&\=\%\#]+search/,"&search");
  raw_search_string = url_encoded_cleanup(raw_search_string);
  //make sure all search param keys are the same...
  raw_search_string = raw_search_string.replace(/\?search/,"&search");
  //split on the search param key...
  var url_search_terms = raw_search_string.split('&search');
  var collected_search_string = "";
  for (var i=0; i<url_search_terms.length; i++) {
  	var volume_test = url_search_terms[i].search("volume") 
	var issue_test = url_search_terms[i].search("issue")
	var fpage_test = url_search_terms[i].search("fpage")
	if (volume_test != -1 || issue_test != -1 || fpage_test != -1) {
		//Don't add to search.
	} else {
		var search_term = url_search_terms[i].split("&");
		var converted_search_term = url_encoded_cleanup(search_term[0]);
		collected_search_string += converted_search_term.replace(/\[.*\]\=|&/," ");
	}
  };
	//Remove white space from beginning of string
	collected_search_string = collected_search_string.replace(/^\s*/g,'');
	  // Replace '+' with '|' for regex
    // Also replace '%20'
	collected_search_string = collected_search_string.replace(/  /g,"\+");
	collected_search_string = collected_search_string.replace(/ /g,"\+");
	return collected_search_string.replace(/\%20|\+/g,"\|");
}

function highlightTextNodes(element, regex, termid) {
  var tempinnerHTML = element.innerHTML;
  // Do regex replace
  // Inject span with class of 'highlighted termX' for google style highlighting
  element.innerHTML = tempinnerHTML.replace(regex,'>$1<span class="search_term_highlight">$2</span>$3<');
}

function url_encoded_cleanup(text) {
  var converted_text = text.replace(/\%5B/,"[");
  converted_text = converted_text.replace(/\%5D/,"]");
  return converted_text;
}
